package com.example.sonone.xianliusuanfa;


/**
 * 最简单的计数器限流算法
 */
public class Counter {
    public long timeStamp = System.currentTimeMillis(); // 当前时间
    public int reqCount = 0; // 初始化计数器
    public final int limit = 5; // 时间窗口内最大请求数
    public final long interval = 1000 * 10; // 时间窗口ms

    /**
     *       true 没有超过 false 超过
     */
    public boolean limit() {
        long now = System.currentTimeMillis();
        if (now < timeStamp + interval) {
            // 在时间窗口内
            reqCount++;
            // 判断当前时间窗口内是否超过最大请求控制数
            return reqCount <= limit;
        } else {
            timeStamp = now;
            // 超时后重置
            reqCount = 1;
            return true;
        }
    }

    public static void main(String[] args) {
        Counter c = new Counter();
        for (int i = 1; i <= 200; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean limit = c.limit();
                    System.out.println(limit);
                }
            }).start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

